Skip to content

Skip the part of width 1 lines outside the image in C - #10629

Open
strike19 wants to merge 1 commit into
python-pillow:mainfrom
strike19:line-clip-in-c
Open

strike19 wants to merge 1 commit into
python-pillow:mainfrom
strike19:line-clip-in-c

Conversation

@strike19

Copy link
Copy Markdown

Follow-up to #10610.

Restricting a line to the image in Python moves its end points. Bresenham's algorithm on the shortened segment does not set the same pixels as on the whole line, so a line that leaves the image is drawn differently from the same line on a larger image that is then cropped. Before #10610, the pixels inside the image were those of the whole line.

from PIL import Image, ImageDraw

xy = [(-17, 3), (41, 29)]

im = Image.new("L", (40, 40))
ImageDraw.Draw(im).line(xy, 255)

large = Image.new("L", (400, 400))
ImageDraw.Draw(large).line([(x + 200, y + 200) for x, y in xy], 255)

assert im.tobytes() == large.crop((200, 200, 240, 240)).tobytes()  # fails on main, 46 pixels differ

I compared 36,000 random lines with integer coordinates (2, 3 and 6 points, solid and with four dash patterns, drawn on 40x40 and cropped from 400x400): 21,734 differ on current main, none with this change.

Changes proposed in this pull request:

  • Keep the end points of width 1 lines and skip the steps before and after the image in C, instead of moving the end points in Python. The error term of the first visible step is calculated directly from the offset on the minor axis, k(i) = floor((2 * minor * i + major) / (2 * major)), so far-away lines are still fast: line((0, 0, 2**30, 1)), with and without dash, takes well under a millisecond.
  • The calculation uses 64-bit integers. Coordinates are 32-bit, so the difference between them can reach 232, and the product of the smaller difference and the number of skipped steps can reach 264.
  • Take the dash position modulo the length of the pattern, so that long dashed lines take no time either. The pattern now continues from the start of the line, instead of starting again where the line enters the image.
  • ImageDraw._restrict_lines now only restricts lines that reach outside the range of C ints, where Liang–Barsky clipping is still needed. Dashed lines of any width go through it as well, since width is ignored with dash.
  • Add tests: test_line_partly_outside_image compares solid and dashed lines that are partly outside the image with the same lines cropped from a larger image, and test_line_far_outside_image_dash draws a dashed line that ends at 2**30. The tests added in Clip width 1 lines to the image #10610 pass unchanged.

The full test suite passes on macOS (arm64, clang), apart from test_imagegrab, which needs the screen recording permission. I have not tested Windows or 32-bit builds.

This is also needed for #10575: with #10610 alone, its translation invariance tests for lines fail.

🤖 Generated with Claude Code

Restricting lines to the image in Python (python-pillow#10610) moves their end points, so
that Bresenham's algorithm sets different pixels inside the image than for the
whole line, and the same line moved by whole pixels no longer gives the same
pixels.

Instead, keep the end points and skip the steps before and after the image
in C. The error term for the first visible step follows from the minor axis
offset k(i) = floor((2 * minor * i + major) / (2 * major)), computed with
64-bit integers, as the coordinates are 32-bit and the product of the
smaller delta and the number of skipped steps can reach 2**64. The dash
position is taken modulo the length of the pattern, so that long dashed lines
take no time either.

Python now only restricts lines that reach outside the range of C ints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@radarhere radarhere added the 🤖-assisted AI-assisted label Nov 25, 2026
@radarhere

radarhere commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Bresenham's algorithm on the shortened segment does not set the same pixels as on the whole line, so a line that leaves the image is drawn differently from the same line on a larger image that is then cropped

Could you make an argument for why it is necessary that they be the same? #10610 was about trying to prevent long lines from using excessive resources. There is a balance between managing resources and providing precision. If a user wants pixel perfect accuracy, I'm not convinced they should be drawing outside of the image in the first place.

Are you personally drawing lines with points outside an image? That would be interesting to hear about. However, if this is merely AI finding an edge case, there are other priorities.

@codspeed

codspeed Bot commented Nov 25, 2026

Copy link
Copy Markdown

Merging this PR will degrade performance by 34.04%

3 warnings

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 6 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚠️ 6 benchmarks with a significant change ran in a different software environment

Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

See affected benchmarks

❌ 6 regressed benchmarks
✅ 662 untouched benchmarks
⏩ 352 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_draw_lines[1237x811-L] 729.9 µs 1,181.3 µs -38.21%
❌ test_draw_lines[1237x811-RGBA] 783.6 µs 1,233.8 µs -36.49%
❌ test_draw_lines[1237x811-LA] 785.7 µs 1,235.3 µs -36.4%
❌ test_draw_lines[1237x811-RGB] 808 µs 1,255.4 µs -35.64%
❌ test_draw_lines_blend[1237x811-255] 1.1 ms 1.6 ms -28.44%
❌ test_draw_lines_blend[1237x811-127] 1.1 ms 1.6 ms -28.37%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing strike19:line-clip-in-c (a106191) with main (925611e)

Open in CodSpeed

Footnotes

  1. 352 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🤖-assisted AI-assisted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants